package com.cxy.contentcenter;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cxy.contentcenter.dao.content.ShareMapper;
import com.cxy.contentcenter.domain.dto.content.ShareDTO;
import com.cxy.contentcenter.domain.dto.user.UserDTO;
import com.cxy.contentcenter.domain.entity.content.Share;
import com.cxy.contentcenter.feignclient.TestBaiduFeignClient;
import com.cxy.contentcenter.feignclient.TestUserCenterFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author: huayushu luming
 * @date: 2020-11-25 14:47
 * @desc:
 **/
@RestController
@Slf4j
public class TestController {
    @Autowired
    private ShareMapper shareMapper;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private TestUserCenterFeignClient testUserCenterFeignClient;
    @Autowired
    private TestBaiduFeignClient testBaiduFeignClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test")
    public Share testInsert(){
        Share share=Share.builder()
                .title("神雕侠侣下天山")
                .cover("xxxxx")
                .author("金庸")
                . buyCount(1)
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        shareMapper.insertSelective(share);
        return share;
    }

    @GetMapping("/test2")
    public List<ServiceInstance> getInstances(){
        //查询指定服务的所有实例信息
        return this.discoveryClient.getInstances("user-center");
    }
    @GetMapping("test-get")
    public UserDTO query(UserDTO userDTO){
        return this.testUserCenterFeignClient.query(userDTO);
    }
    @GetMapping("baidu")
    public String baiduIndex(){
        return this.testBaiduFeignClient.index();
    }
    @Autowired
    private TestService testService;
    @GetMapping("test-a")
    public String testA(){
        this.testService.common();
        return "test-a";
    }
    @GetMapping("test-b")
    public String testB(){
        this.testService.common();
        return "test-b";
    }

    @GetMapping("/test-sentinel-resource")
    @SentinelResource(value = "test-sentinel-api",blockHandler="block",fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false)String a){
        if(StringUtils.isEmpty(a)){
            throw new IllegalArgumentException("a cannot be blank.");
        }
        return  a;
    }

    /**
     * 处理限流或降级
     * @param a
     * @param e
     * @return
     */
    public String block(String a, BlockException e){
        log.warn("限流，或者降级了 block",e);
        return "限流，或者降级了";
    }

    /**
     * 处理降级
     * @param a
     * @param e
     * @return
     */
    public String fallback(String a, BlockException e){
        log.warn("限流，或者降级了 fallback",e);
        return "限流，或者降级了";
    }

//    @Autowired
//    private Source source;
//    @Autowired
//    private MySource mySource;
//    @GetMapping("/test-stream")
//    public String testStream(){
//        this.source.output().send(
//                MessageBuilder
//                        .withPayload("消息体")
//                .build());
//                return "success";
//    }
//
//    @GetMapping("/test-stream2")
//    public String testStream2(){
//        this.mySource.output().send(
//                MessageBuilder
//                        .withPayload("消息体2")
//                        .build());
//        return "success2";
//    }


    @GetMapping("/tokenRelay/{userId}")
    public ResponseEntity<UserDTO> tokenRelay(@PathVariable Integer userId, HttpServletRequest request) {
        String token = request.getHeader("X-Token");
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Token", token);

        return this.restTemplate
                .exchange(
                        "http://user-center/users/{userId}",
                        HttpMethod.GET,
                        new HttpEntity<>(headers),
                        UserDTO.class,
                        userId
                );
    }
}
